package com.cg.util;

import com.cg.config.TokenFactory;
import com.cg.param.WechatUrl;
import com.cg.pojo.TbWeChatUser;
import com.github.binarywang.java.emoji.EmojiConverter;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.protocol.Protocol;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.*;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.SecureRandom;
import java.util.Date;

/**
 * 
 * @author cg
 * 通用工具类
 */
public class WeiXinUtils {
	private static EmojiConverter emojiConverter = EmojiConverter.getInstance();
	private static Logger log= LoggerFactory.getLogger(WeiXinUtils.class);
	//凭证获取
	public final static String token_url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
	/**
	 * 发送https请求
	 * @param requestUrl 请求地址
	 * @param requestMethod 请求方式（get,post）
	 * @param outputStr 提交的数据
	 * @return JSONObject(调用者通过JSONObject.get(key)的方式获json的属性值)
	 */
	public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr){
		JSONObject jsonObject=null;
		try {
			//创建SSLContext对象，并使用我们指定的信任管理器初始化
			TrustManager[] tm={new MyX509TrustManager()};
			SSLContext sslContext=SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new SecureRandom());
			//从上述SSLContext对象中得到SSLSocketFactory对象
			SSLSocketFactory ssf=sslContext.getSocketFactory();
			
			URL url=new URL(requestUrl);
			HttpsURLConnection conn=(HttpsURLConnection) url.openConnection();
			conn.setSSLSocketFactory(ssf);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			//设置请求方式
			conn.setRequestMethod(requestMethod);
			
			if(null!=outputStr){
				OutputStream outputStream = conn.getOutputStream();
				//注意编码方式
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}
			
			//从输入流中读取返回数据
			InputStream inputStream = conn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String str=null;
			StringBuffer sb=new StringBuffer();
			while((str=bufferedReader.readLine()) !=null){
				sb.append(str);
			}
			
			//释放资源
			bufferedReader.close();
			inputStreamReader.close();
			inputStream.close();
			inputStream=null;
			conn.disconnect();
			jsonObject=JSONObject.fromObject(sb.toString());
		} catch (ConnectException e) {
			log.error("链接超时：{}",e);
		}catch(Exception e){
			log.error("https请求异常：{}",e);
		}
		return jsonObject;
	}
	
	
	


   //根据文件类型，返回扩展名
	public static String getFileExt(String contentType) {
		String fileExt="";
		if("image/jpeg".equals(contentType)){
			fileExt=".jpg";
		}else if("audio/mpeg".equals(contentType)){
			fileExt=".mp3";
		}else if("audio/amr".equals(contentType)){
			fileExt=".amr";
		}else if("video/mp4".equals(contentType)){
			fileExt=".mp4";
		}
		return fileExt;
	}
	 
	/**
	 * utf-8加密
	 * @param source
	 * @return
	 */
	public static String urlEncodeUTF8(String source){
		String result=source;
		try {
			result=URLEncoder.encode(source,"utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 发送http请求
	 * @param reqUrl
	 * @return JSONObject
	 */
	public static String sendHttpUrl(String reqUrl){
		String getURL=reqUrl;
		URL getUrl;
		JSONObject jsonObject=null;
		StringBuffer sb=null;
		try {
			getUrl = new URL(getURL);
			HttpURLConnection connection=(HttpURLConnection) getUrl.openConnection();
			connection.connect();
			BufferedReader reader=new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
			sb=new StringBuffer();
			String line="";
			while((line=reader.readLine())!=null){
				sb.append(line);
			}
			reader.close();
			connection.disconnect();
			 
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return sb.toString();
	}
     //post请求
	public static String postFileViaHttps(String requestUrl, Part[] parts) {
		String resJson = null;

		PostMethod post = new PostMethod(requestUrl);
		post.setRequestHeader("Connection", "Keep-Alive");
		post.setRequestHeader("Cache-Control", "no-cache");
		// FilePart media = null;
		HttpClient httpClient = new HttpClient();

		// 信任任何类型的证书
		Protocol myhttps = new Protocol("https", new MySSLProtocolSocketFactory(), 443);
		Protocol.registerProtocol("https", myhttps);

		try {
			// media = new FilePart("media", file);
			// Part[] parts = new Part[] { media };
			MultipartRequestEntity entity = new MultipartRequestEntity(parts, post.getParams());
			post.setRequestEntity(entity);
			int status = httpClient.executeMethod(post);
			if (status == HttpStatus.SC_OK) {
				resJson = post.getResponseBodyAsString();
			}
		} catch (FileNotFoundException e) {
			System.out.println("postFileViaHttps error:{}"+ e);
		} catch (HttpException e) {
			System.out.println("postFileViaHttps error:{}"+ e);
		} catch (IOException e) {
			System.out.println("postFileViaHttps error:{}"+ e);
		}
		return resJson;
	}
	//调用微信接口通过openid获取用户信息
	public static TbWeChatUser getTbWeChatUser(StringRedisTemplate stringRedisTemplate, String openId){
		String accessToken = TokenFactory.getAccessToken(stringRedisTemplate);
		String url= WechatUrl.GET_USER_INFO.replace("ACCESS_TOKEN",accessToken).replace("OPENID",openId);
		JSONObject jsonObject = WeiXinUtils.httpsRequest(url, "GET", null);
		TbWeChatUser tbWeChatUser = new TbWeChatUser();
		tbWeChatUser.setSubscribe(1);
		tbWeChatUser.setOpenId(jsonObject.getString("openid"));
		String nickname = emojiConverter.toAlias(jsonObject.getString("nickname"));
		tbWeChatUser.setNickName(nickname);
		tbWeChatUser.setSex(jsonObject.getString("sex"));
		tbWeChatUser.setLanguage(jsonObject.getString("language"));
		tbWeChatUser.setCity(jsonObject.getString("city"));
		tbWeChatUser.setProvince(jsonObject.getString("province"));
		tbWeChatUser.setCountry(jsonObject.getString("country"));
		tbWeChatUser.setHeadImgUrl(jsonObject.getString("headimgurl"));
		tbWeChatUser.setSubscribeTime(new Date());
		tbWeChatUser.setRemark(jsonObject.getString("remark"));
		tbWeChatUser.setGroupId(jsonObject.getString("groupid"));
		JSONArray tagid_list = jsonObject.getJSONArray("tagid_list");
		String s = JSONHelper.array2json(tagid_list);
		tbWeChatUser.setTagidList(s);
		tbWeChatUser.setCreateDate(new Date());
		return tbWeChatUser;
	}
}
